package com.yylany.auth.service;

import com.yylany.auth.client.UserClient;
import com.yylany.auth.config.JwtProperties;
import com.yylany.auth.entity.UserInfo;
import com.yylany.auth.util.JwtUtils;
import com.yylany.pojo.TbUser;
import com.yylany.vo.LoginResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;


/**
 * Description:
 *
 * @author <a href="mailto:17777502615@163.com">yaoyonglong</a>
 * @date 2018/12/17
 * @since 1.0.0
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);

    /**
     * 根据传过来的 手机号 以及密码进行登录封装
     *
     * @param mobile
     * @param password
     * @return
     */
    public LoginResult login(String mobile, String password) {
        try {
            // 查询用户信息
            ResponseEntity<TbUser> resp = this.userClient.queryUser(mobile, password);
            if (!resp.hasBody()) {
                return null;
            }
            // 查询成功，获取用户
            TbUser user = resp.getBody();
            // 生成token
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId().longValue());
            userInfo.setUsername(user.getName());
            String token = JwtUtils.generateToken(userInfo,
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            // 生成返回信息
            LoginResult baseResult = new LoginResult();
            baseResult.setToken(token);
            baseResult.setName(user.getName());

            return baseResult;
        } catch (Exception e) {
            logger.error("生成token失败，用户名：{}", mobile, e);

        }
        return null;

    }

}
